// utils/api.js
const API_URL = 'https://spark-api-open.xf-yun.com/v1/chat/completions';
const API_KEY = 'Bearer isosWTGpyHEjZENnTgYk:uyyfKoybBOcgruMGsEgv'; // 替换为你的 APIPassword

function sendMessage(messages, onDataReceived, model = '4.0Ultra') {
  return new Promise((resolve, reject) => {
    wx.request({
      url: API_URL,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': API_KEY,
        'host': 'spark-api-open.xf-yun.com',
      },
      data: {
        model: model,
        messages: messages,
      },
      success(res) {
        if (res.statusCode === 200) {
          // 假设 API 返回的数据是分段的
          const data = res.data.choices[0].message.content;
          onDataReceived(data); // 调用回调函数逐段处理数据
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

module.exports = {
  sendMessage,
};